package com.example.archive.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.archive.entity.RestrictedArchiveRequest;
import com.example.archive.mapper.RestrictedArchiveRequestMapper;
import com.example.archive.service.RestrictedArchiveRequestService;
import com.example.archive.service.SystemLogService;
import com.example.archive.util.PageParam;
import com.example.archive.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 受限档案访问申请服务实现类
 * 处理受限档案申请的具体业务逻辑
 */
@Service
public class RestrictedArchiveRequestServiceImpl extends ServiceImpl<RestrictedArchiveRequestMapper, RestrictedArchiveRequest> 
        implements RestrictedArchiveRequestService {
    
    @Autowired
    private SystemLogService systemLogService;
    
    @Override
    public Result<Boolean> submitRequest(RestrictedArchiveRequest request) {
        try {
            // 设置申请时间和默认状态
            request.setRequestTime(new Date());
            request.setApprovalStatus("pending");
            
            // 保存申请
            boolean success = save(request);
            
            if (success) {
                // 记录系统日志
                systemLogService.recordLog(request.getUserId(), "提交受限档案访问申请", 
                    "申请访问档案ID：" + request.getArchiveId() + "，申请原因：" + request.getReason());
                return Result.success(true);
            } else {
                return Result.fail(500, "提交申请失败");
            }
        } catch (Exception e) {
            return Result.fail(500, "提交申请失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<IPage<RestrictedArchiveRequest>> listRequests(PageParam pageParam, String status, Integer userId, Integer approverId) {
        try {
            Page<RestrictedArchiveRequest> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
            
            IPage<RestrictedArchiveRequest> result = baseMapper.selectRequestsWithDetails(
                page, status, userId, approverId, pageParam.getSearch()
            );
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail(500, "查询申请列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> approveRequest(Integer requestId, Integer approverId, String approvalStatus, String notes) {
        try {
            RestrictedArchiveRequest request = getById(requestId);
            if (request == null) {
                return Result.fail(404, "申请不存在");
            }
            
            if (!"pending".equals(request.getApprovalStatus())) {
                return Result.fail(400, "该申请已处理，无法重复审批");
            }
            
            // 更新审批信息
            request.setApproverId(approverId);
            request.setApprovalStatus(approvalStatus);
            request.setApprovalTime(new Date());
            request.setNotes(notes);
            
            boolean success = updateById(request);
            
            if (success) {
                // 记录系统日志
                String action = "approved".equals(approvalStatus) ? "批准" : "拒绝";
                systemLogService.recordLog(approverId, action + "受限档案访问申请", 
                    "申请ID：" + requestId + "，档案ID：" + request.getArchiveId());
                return Result.success(true);
            } else {
                return Result.fail(500, "审批失败");
            }
        } catch (Exception e) {
            return Result.fail(500, "审批失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<RestrictedArchiveRequest> getRequestDetail(Integer requestId) {
        try {
            // 直接根据ID查询基本信息
            RestrictedArchiveRequest request = getById(requestId);
            if (request == null) {
                return Result.fail(404, "申请不存在");
            }
            
            // 查询详细信息（包含关联字段）
            Page<RestrictedArchiveRequest> page = new Page<>(1, 1);
            IPage<RestrictedArchiveRequest> result = baseMapper.selectRequestsWithDetails(
                page, null, null, null, null
            );
            
            // 从结果中找到对应的记录
            for (RestrictedArchiveRequest item : result.getRecords()) {
                if (item.getRequestId().equals(requestId)) {
                    return Result.success(item);
                }
            }
            
            // 如果没找到详细信息，返回基本信息
            return Result.success(request);
        } catch (Exception e) {
            return Result.fail(500, "获取申请详情失败：" + e.getMessage());
        }
    }
} 